package com.shiny.concurrency4java.lock;

import com.shiny.concurrency4java.annoations.ThreadSafe;
import com.shiny.concurrency4java.util.Constant;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@ThreadSafe
public class SyncExample {
    private long v1 = 0L;

    public synchronized long get(){
        return v1;
    }

    public synchronized void set(long v) {
        this.v1 = v;
    }

    public void getAndIncrement(){
        synchronized(this){
            long temp = get();
            temp += 1L;
            set(temp);
        }
    }

    public static void main(String[] args) throws Exception {
        SyncExample syncexample = new SyncExample();
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(Constant.threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(Constant.clientTotal);
        for (int i = 0; i < Constant.clientTotal ; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    syncexample.getAndIncrement();
                    semaphore.release();

                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("v1:{}",syncexample.get());
    }


}
